# -*- coding: utf-8 -*-

import os
from typing import List, Optional, Tuple

import pytest
import torch
import triton
import triton.language as tl
from fla.ops.utils.op import exp

from fla.utils import assert_close
from fla.ops.gated_delta_rule.wy_fast import bwd_prepare_wy_repr


@triton.heuristics({
    'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
    configs=[
        triton.Config({}, num_warps=num_warps, num_stages=num_stages)
        for num_warps in [2, 4]
        for num_stages in [2, 3, 4]
    ],
    key=['H', 'K', 'V', 'BT', 'BK', 'BV', 'IS_VARLEN'],
)
@triton.jit(do_not_specialize=['T'])
def prepare_wy_repr_bwd_kernel(	
    k,	
    v,	
    beta,	
    g,	
    A,	
    dw,	
    du,	
    dk,	
    dv,	
    dbeta,	
    dg,	
    cu_seqlens,	
    chunk_indices,	
    T,	
    H: tl.constexpr,	
    K: tl.constexpr,	
    V: tl.constexpr,	
    BT: tl.constexpr,	
    BK: tl.constexpr,	
    BV: tl.constexpr,	
    IS_VARLEN: tl.constexpr	
):	
    i_t, i_bh = tl.program_id(0), tl.program_id(1)	
    i_b, i_h = i_bh // H, i_bh % H	
    if IS_VARLEN:	
        i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)	
        bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)	
        T = eos - bos	
    else:	
        bos, eos = i_b * T, i_b * T + T	

    p_beta = tl.make_block_ptr(beta + (bos*H + i_h), (T,), (H,), (i_t * BT,), (BT,), (0,))	
    p_g = tl.make_block_ptr(g + (bos*H + i_h), (T,), (H,), (i_t * BT,), (BT,), (0,))	
    p_A = tl.make_block_ptr(A + (bos*H + i_h) * BT, (BT, T), (1, H*BT), (0, i_t * BT), (BT, BT), (0, 1))	

    b_A = tl.load(p_A, boundary_check=(0, 1))	
    b_beta = tl.load(p_beta, boundary_check=(0,))	
    b_g = tl.load(p_g, boundary_check=(0,))	
    b_g_exp = tl.exp(b_g)	

    b_dbeta = tl.zeros([BT], dtype=tl.float32)	
    b_dA = tl.zeros([BT, BT], dtype=tl.float32)	
    b_dg = tl.zeros([BT], dtype=tl.float32)	

    for i_k in range(tl.cdiv(K, BK)):	
        p_k = tl.make_block_ptr(k + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))	
        p_dk = tl.make_block_ptr(dk + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))	
        p_dw = tl.make_block_ptr(dw + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))	
        b_k = tl.load(p_k, boundary_check=(0, 1))	
        b_k_beta_g = (b_k * b_beta[:, None] * b_g_exp[:, None]).to(b_k.dtype)	
        b_dw = tl.load(p_dw, boundary_check=(0, 1))	
        b_dA += tl.dot(b_dw, tl.trans(b_k_beta_g))	
        b_dk_beta_g = tl.dot(b_A, b_dw)	
        b_dk = b_dk_beta_g * b_beta[:, None] * b_g_exp[:, None]	
        b_dbeta += tl.sum(b_dk_beta_g * b_k * b_g_exp[:, None], 1)	
        b_dg += tl.sum(b_dk_beta_g * b_k * b_g_exp[:, None] * b_beta[:, None], 1)	
        tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))	

    for i_v in range(tl.cdiv(V, BV)):	
        p_v = tl.make_block_ptr(v + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))	
        p_dv = tl.make_block_ptr(dv + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))	
        p_du = tl.make_block_ptr(du + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))	
        b_v = tl.load(p_v, boundary_check=(0, 1))	
        b_v_beta = (b_v * b_beta[:, None]).to(b_v.dtype)	
        b_du = tl.load(p_du, boundary_check=(0, 1))	
        b_dA += tl.dot(b_du, tl.trans(b_v_beta))	
        b_dv_beta = tl.dot(b_A, b_du)	
        b_dv = b_dv_beta * b_beta[:, None]	
        b_dbeta += tl.sum(b_dv_beta * b_v, 1)	
        tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))	

    o_t = i_t * BT + tl.arange(0, BT)	
    m_t = o_t < T	
    m_A = (o_t[:, None] > o_t[None, :]) & (m_t[:, None] & m_t)	
    b_dA = tl.where(m_A, b_dA, 0)	
    b_dA = tl.dot(b_dA.to(b_A.dtype), b_A)	
    b_dA = tl.dot(b_A, b_dA.to(b_A.dtype))	
    b_dA = tl.where(m_A, -b_dA * exp(b_g[:, None] - b_g[None, :]), 0)	
    b_dA = b_dA.to(k.dtype.element_ty)	
    b_A = tl.zeros([BT, BT], dtype=tl.float32)	

    for i_k in range(tl.cdiv(K, BK)):	
        p_k = tl.make_block_ptr(k + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))	
        p_dk = tl.make_block_ptr(dk + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))	
        b_k = tl.load(p_k, boundary_check=(0, 1))	
        b_dk = tl.load(p_dk, boundary_check=(0, 1))	
        b_k_beta = (b_k * b_beta[:, None]).to(b_k.dtype)	
        b_A += tl.dot(b_k_beta, tl.trans(b_k))	
        b_dk_beta = tl.dot(b_dA, b_k)	
        b_dbeta += tl.sum(b_dk_beta * b_k, 1)	
        b_dk += tl.dot(tl.trans(b_dA), b_k_beta)	
        b_dk += b_dk_beta * b_beta[:, None]	
        tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))	

    b_dA_A = b_dA * b_A	
    b_dg += tl.sum(b_dA_A, axis=1) - tl.sum(b_dA_A, axis=0)	
    p_dg = tl.make_block_ptr(dg + (bos*H + i_h), (T,), (H,), (i_t * BT,), (BT,), (0,))	
    p_dbeta = tl.make_block_ptr(dbeta + (bos*H + i_h), (T,), (H,), (i_t * BT,), (BT,), (0,))	
    tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0,))	
    tl.store(p_dbeta, b_dbeta.to(p_dbeta.dtype.element_ty), boundary_check=(0,))


def prepare_wy_repr_bwd(
    k: torch.Tensor,
    v: torch.Tensor,
    beta: torch.Tensor,
    A: torch.Tensor,
    dw: torch.Tensor,
    du: torch.Tensor,
    g: torch.Tensor = None,
    cu_seqlens: Optional[torch.LongTensor] = None,
    chunk_size: int = 16,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    B, T, H, K, V = *k.shape, v.shape[-1]
    BT = chunk_size
    chunk_indices = None
    NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
    CONST_TILING = 32
    BK = min(max(triton.next_power_of_2(K), 16), CONST_TILING)
    BV = min(max(triton.next_power_of_2(V), 16), CONST_TILING)

    dk = torch.empty_like(k)
    dv = torch.empty_like(v)
    dg = torch.empty_like(g) if g is not None else None
    dbeta = torch.empty_like(beta)
    prepare_wy_repr_bwd_kernel[(NT, B * H)](
        k=k,
        v=v,
        beta=beta,
        g=g,
        A=A,
        dw=dw,
        du=du,
        dk=dk,
        dv=dv,
        dbeta=dbeta,
        dg=dg,
        cu_seqlens=cu_seqlens,
        chunk_indices=chunk_indices,
        T=T,
        H=H,
        K=K,
        V=V,
        BT=BT,
        BK=BK,
        BV=BV,
    )
    return dk, dv, dbeta, dg


@pytest.mark.parametrize(
    ('B', 'T', 'H', 'D', 'chunk_size'),
    [
        pytest.param(*test, id="B{}-T{}-H{}-D{}-chunk_size{}".format(*test))
        for test in [
            (1, 1024, 32, 128, 16),
            (1, 4096, 32, 128, 16),
        ]
    ]
)
def test_recompute_w_u_fwd(B, T, H, D, chunk_size):

    device = "npu:0"
    device_dtype = torch.float32

    k = torch.randn((B, T, H, D), device=device, dtype=device_dtype)
    v = torch.randn((B, T, H, D), device=device, dtype=device_dtype)
    beta = torch.randn((B, T, H), device=device, dtype=device_dtype)
    A = torch.randn((B, T, H, chunk_size), device=device, dtype=device_dtype)
    g = torch.randn((B, T, H), device=device, dtype=device_dtype)
    dw = torch.randn((B, T, H, D), device=device, dtype=device_dtype)
    du = torch.randn((B, T, H, D), device=device, dtype=device_dtype)

    ref_dk, ref_dv, ref_dbeta, ref_dg = prepare_wy_repr_bwd(
        k=k,
        v=v,
        beta=beta,
        A=A,
        dw=dw,
        du=du,
        g=g,
        cu_seqlens=None,
        chunk_size=chunk_size,
    )
    
    dk, dv, dbeta, dg = bwd_prepare_wy_repr(
        k=k,
        v=v,
        beta=beta,
        A=A,
        dw=dw,
        du=du,
        g=g,
        cu_seqlens=None,
        chunk_size=chunk_size,
    )

    assert_close('dk', ref_dk, dk, 0.001)
    assert_close('dv', ref_dv, dv, 0.001)
    assert_close('dbeta', ref_dbeta, dbeta, 0.001)
    assert_close('dg', ref_dg, dg, 0.001)